package com.ckzp.weixin.service;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * Created by 51594 on 2023/4/3.
 */
public class ServiceTool {

    public static String TOKEN = "952636897";
    public static String AES_KEY = "ylxtqsLQvHuwIYYtnuuVPa3jqnz5KqWH8Y4hCS4miHd";


    /**
     * 微信接口SIGN验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        if (signature == null || timestamp == null || nonce == null) return false;
        String[] tmpArr = {TOKEN, timestamp, nonce};
        Arrays.sort(tmpArr);
        String tmpStr = ArrayToString(tmpArr);
        tmpStr = SHA1Encode(tmpStr);
        if (tmpStr.equalsIgnoreCase(signature)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 数组转字符串
     *
     * @param arr
     * @return
     */
    public static String ArrayToString(String[] arr) {
        StringBuffer bf = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            bf.append(arr[i]);
        }
        return bf.toString();
    }

    /**
     * sha1加密
     *
     * @param sourceString
     * @return
     */
    public static String SHA1Encode(String sourceString) {
        String resultString = null;
        try {
            resultString = new String(sourceString);
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            resultString = byte2hexString(md.digest(resultString.getBytes()));
        } catch (Exception ex) {
        }
        return resultString;
    }

    /**
     * @param bytes
     * @return
     */
    public static String byte2hexString(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString().toUpperCase();
    }

    /**
     * 取得消息或事件关键词，对应数据库中事件执行
     *
     * @param req
     * @return
     */
    public static String getMsgTypeKey(ServiceRequest req) {
        if (req != null) {
            String msgType = req.getMsgType();
            if ("event".equals(msgType)) {
                return "event_" + req.getEvent();
            } else {
                return msgType;//反回文本及内容
            }
        }
        return "none";//未配对消息事件
    }

}
